<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-22
 * Time: 11:32:23
 * Info:
 */

namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AccessControl implements MiddlewareInterface
{

    public function process(Request $request, callable $handler): Response
    {
        $response = $request->method() == 'OPTIONS' ? response('') : $handler($request);
        $response->withHeaders([
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin'      => $request->header('Origin', '*'),
            'Access-Control-Allow-Methods'     => '*',
            'Access-Control-Allow-Headers'     => '*',
        ]);

        //判断后台禁止ip，如果存在，禁止访问全站。
        $res = $this->checkIp();
        if ( ! empty($res) && $res['code'] === 0) {
            return error_json($res['msg']);
        }

        return $response;
    }

    private function checkIp()
    {
        $ip                = get_client_ip();
        $admin_prohibit_ip = get_config('admin_prohibit_ip');
        $arr               = array_filter(explode(',', $admin_prohibit_ip));
        if ( ! empty($arr)) {
            foreach ($arr as $val) {
                //是否是IP段
                if (strpos($val, '*')) {
                    if (strpos($ip, str_replace('.*', '', $val)) !== false) {
                        return (['code' => 0, 'msg' => '你在IP禁止段内,全站禁止访问！~~~']);
                    }
                } else {
                    //不是IP段,用绝对匹配
                    if ($ip == $val) {
                        return (['code' => 0, 'msg' => 'IP地址绝对匹配,全站禁止访问！~~~']);
                    }
                }
            }
        }

        return ['code' => 200];
    }

}
